<?php
// $Id: upload.php 167 2012-02-03 10:06:17Z tomqin@gmail.com $

defined('IN_ADMIN') or exit('Access Denied!');

class Upload_Controller extends AdminController{

	function onThumb(){
		if(array_get_string($_POST, 'dosubmit')){
			$width    = array_get_int($_POST, 'width');
			$height   = array_get_int($_POST, 'height');
			$original = array_get_bool($_POST, 'original');
			echo $this->uploadThumb('picture', $width, $height, $original);
		}
	}

	function uploadThumb($file, $width, $height, $original = false){
		Base::loadLibrary('Upload');

		$option = array(
			'max_length'       => 2048000,
			'allow_type'       => 'image',
			'check_image'      => true,
			'image_min_width'  => $width,
			'image_max_width'  => 3000,
			'image_min_height' => $height,
			'image_max_height' => 3000,
		);
		$upload = new Upload($file, $option);
		$result = $upload->uploadFile();

		if($result == UPLOAD_ERR_OK){
			$error = false;
		}else{
			switch($result){
				case UPLOAD_ERR_INI_SIZE :
				case UPLOAD_ERR_FORM_SIZE :
				case UPLOAD_ERR_FILE_SIZE :
					$error = '图片大小必须在 ' . convert_size($option['max_length']) . ' 以内';
				break;

				case UPLOAD_ERR_FILE_TYPE :
				case UPLOAD_ERR_IMAGE_TYPE :
					$error = '图片格式错误，只能为 png/jpg/gif 格式！';
				break;
				case UPLOAD_ERR_IMAGE_SMALL :
					$error = '图片尺寸太小，请保证大于 ' .$option['image_min_width']. 'x' .$option['image_min_height']. '';
				break;
				case UPLOAD_ERR_IMAGE_LARGE :
					$error = '图片尺寸太大，请保证小于 ' .$option['image_max_width']. 'x' .$option['image_max_height']. '';
				break;

				case UPLOAD_ERR_PARTIAL :
				case UPLOAD_ERR_NO_FILE :
				case UPLOAD_ERR_NO_TMP_DIR :
				case UPLOAD_ERR_CANT_WRITE :
				case UPLOAD_ERR_EXTENSION :
					$error = '图片上传错误，请重试(' . $result . ')！';
					break;
				case UPLOAD_ERR_UNKNOWN :
				default:
					$error = '图片上传错误，请重试！';
			}
		}

		if(!$error){
			Base::loadLibrary('image');
			Base::loadLibrary('file');

			$filename = date('Y/m/YmdHis').'_'.mt_rand(1000, 9999);
			$fileext  = fileext($upload->file['name']);

			File::mkdir(UPLOAD_PATH.dirname($filename));

			move_uploaded_file($upload->file['tmp_name'], UPLOAD_PATH.$filename.'.'.$fileext);
			$image = Image::createFromFile(UPLOAD_PATH.$filename.'.'.$fileext, $fileext);
			$image->thumb($width, $height)->saveAsJpeg(UPLOAD_PATH.$filename.'.thumb.jpg');
		}

		$data = array(
			'url' => $filename.'.thumb.jpg',
			'localname' => $upload->file['name'],
			'id'  => md5($upload->file['name']),
		);
		return json_encode(array(
			'err' => $error,
			'msg' => $data,
		));
	}
}
?>